"use strict"
const mvc = require("cosjs.mvc");



exports.page = function () {
    let $page = this.get('page', 'int') || 1;
    let $size = this.get('size', 'int') || 20;
    let $sort = this.get('sort') || 'sid';
    let $order = this.get('order') || 'desc';
    let dbsort = {};
    if ($sort) {
        dbsort[$sort] = $order == 'desc' ? -1 : 1;
    }

    let cashModel = this.config.get("cash.model");
    let cashFormat = this.config.get("cash.format");

    let body = this.req.body;
    let format = mvc.format(cashFormat);

    let query = this.library.call(this, 'jqgrid/query', body, format);
    let option = {};
    let model = this.model.mongo(cashModel, this.sid);
    return model.page(query, $page, $size, dbsort, option);
}


exports.save = function () {
    let act = this.get('act');
    switch (act) {
        case "edit":
            return edit.call(this);
        default:
            return this.error("req.act[" + act + "] not exist ");
    }
}


function edit() {
    let id = this.get('id', 'string');
    if (!id) {
        return this.error('id不能为空');
    }

    let cashFormat = this.config.get("cash.format");

    //let status = this.get("status","int");
    let setStatus = 0;
    let model = this.model.mongo(cashFormat, this.sid);
    return model.get(id).then(ret => {
        if (!ret) {
            return this.error("cash not exist")
        }
        else if (ret['status'] >= 9) {
            return this.success("ok")
        }
        setStatus = 1;
        return model.set(id, 'status', 2).then(() => ret);
    }).then(ret => {
        ret['orderid'] = ret["_id"];
        ret['opensdk'] = this.config.get("cash.opensdk");
        let api = '/cash/';
        return this.library('spirit/gzone', api, ret);
    }).then(() => {
        return model.set(id, 'status', 9);
    }).catch(err => {
        if (setStatus) {
            model.set(id, 'status', 0);
        }
        return Promise.reject(err);
    })
}
